package com.man;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.std.DB;
import com.std.Order;
import com.std.ShopCar;

public class OrderCtrl {
	private DB db;
	public OrderCtrl(){
		db=new DB();
	}
	public void insertItem(String username,List<ShopCar> shopCarList) {
		if(shopCarList.size()==0) return;
		double totalFee=0;
		Iterator<ShopCar> iterator=shopCarList.iterator();
		while(iterator.hasNext()){
			ShopCar shopCar=iterator.next();
			totalFee+=shopCar.getPrice()*shopCar.getAmount();
		}
		String sql="insert into order_t(order_id,username,submit_time,total_fee,is_send,is_payoff) values(order_s.nextval,?,current_date,?,?,?)";
		Object []params={username,totalFee,0,0};
		db.execute(sql, params);
		sql="insert into order_item_t values(order_item_s.nextval,order_s.currval,?,?)";
		String sql2="update book_t set remainder=remainder-? where book_id=?";
		iterator=shopCarList.iterator();
		while(iterator.hasNext()){
			ShopCar shopCar=iterator.next();
			params[0]=shopCar.getBookId();
			params[1]=shopCar.getAmount();
			params[2]=null;
			db.execute(sql, params);
			params[0]=shopCar.getAmount();
			params[1]=shopCar.getBookId();
			params[2]=null;
			db.execute(sql2, params);
		}
	}
	public void handleSend(int orderId,int isSend) {
		String sql="update order_t set consignment_time=current_date,is_send=? where order_id=?";
		Object []params={isSend,orderId};
		db.execute(sql, params);
	}
	public void handlePayoff(int orderId,int isPayoff) {
		String sql="update order_t set is_payoff=? where order_id=?";
		Object []params={isPayoff,orderId};
		db.execute(sql, params);
	}
	public void deleteItem(int orderId) {
		String sql="delete from order_t where order_id=?";
		Object []params={orderId};
		db.execute(sql, params);
		sql="delete from order_item_t where order_id=?";
		db.execute(sql, params);
	}
	public List<Order> getItems(String username) {
		String sql="select * from order_t";
		Object []params=new Object[1];
		if(username!=null&&username!=""){
			sql=sql+" where username=?";
			params[0]=username;
		}
		db.execute(sql, params);
		List<Order> orderList=new ArrayList<Order>();
		ResultSet rs=db.getResultset();
		try {
			while(rs.next()){
				Order order=new Order();
				order.setConsignmentDate(rs.getDate("consignment_time"));
				order.setIsPayoff(rs.getInt("is_payoff"));
				order.setIsSend(rs.getInt("is_send"));
				order.setOrderId(rs.getInt("order_id"));
				order.setSubmitTime(rs.getDate("submit_time"));
				order.setTotalFee(rs.getDouble("total_fee"));
				order.setUsername(rs.getString("username"));
				orderList.add(order);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return orderList;
	}
	public void close() {
		db.close();
	}
}
